package com.aaron.leetcode.lc19;

import com.aaron.leetcode.lc23.ListNode;

import java.util.Arrays;
import java.util.List;

/**
 * @author liurong
 * @date 2022/2/14 16:56
 * @version:
 */
//给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
public class Solution19_1 {
    ListNode start;

    {
        start = new ListNode(-1);
        ListNode p = start;
        List<Integer> list = Arrays.asList(14, 17, 25, 29);
        for (int i = 0; i < list.size(); i++) {
            ListNode nextNode = new ListNode(list.get(i));
            p.next = nextNode;
            p = nextNode;
        }
        start = start.next;
        p = start;
        while (p != null) {
            System.out.print(p.val + " ");
            p = p.next;
        }
        System.out.println();
    }

    //1<=n<=size
    public ListNode removeNthFromEnd(ListNode head, int n) {

        if (null == head) {
            return head;
        }

        ListNode ans = head, p1 = head, p2 = head;
        for (int i = 0; i < n; i++) {
            p2 = p2.next;
        }

        //说明n=size,删除头结点，直接返回head.next
        if (null == p2) {
            return head.next;
        }

        while (null != p2.next) {
            p1 = p1.next;
            p2 = p2.next;
        }

        p1.next = p1.next.next;
        return head;
    }


    public static void main(String[] args) {
        Solution19_1 solution19_1 = new Solution19_1();
        ListNode p = solution19_1.removeNthFromEnd(solution19_1.start,4);

        while (p != null) {
            System.out.print(p.val + " ");
            p = p.next;
        }
        System.out.println();
    }

}

